#include "StdAfx.h"
#include "EntityControl.h"

#include "ControlLogic.h"
#include "Controller.h"
#include "PhysicsEntity.h"

EntityControl::EntityControl(float hp)
{
	HitPoint = hp;
}

EntityControl::EntityControl(const Ogre::Entity& EntityControl, float hp)
	:Ogre::Entity(EntityControl)
{
	HitPoint = hp;
	//TriggerList = new std::vector<Trigger*>;
}

EntityControl::~EntityControl(void)
{
	//this->getParentSceneNode()->detachObject(this);
	////this->getParentSceneNode()->removeAllChildren();

	//Ogre::Entity* model = this->getModelActor();
	//model->getParentSceneNode()->detachObject(model);
	////delete model;

	//PhysicsEntity* phy = this->getPhysicsActor();
	//phy->getParentSceneNode()->detachObject(phy);
	////phy->getParentSceneNode()->removeAllChildren();
	////delete phy;

	//delete controller;

	//std::vector<Trigger*>::iterator i = TriggerList.begin();
	//while(i != TriggerList.end())
	//{
	//	delete *i;
	//	i++;
	//}
}

void EntityControl::makeController(ControlLogic* logic)
{
	controller = logic->makeController();
}

Controller* EntityControl::control(const ControlContext& context)
{
	if(controller)
		controller->apply(this, context);

	std::vector<Trigger*>::iterator i = TriggerList.begin();
	while( i!=TriggerList.end())
	{
		bool res = (*i)->UseTrigger(this);
		if(res)
			i = TriggerList.erase(i);
		else
		 i++;
	}

	return controller;
}

// render
// animate

PhysicsEntity* EntityControl::getPhysicsActor()
{
	return bulletActor;
}

void EntityControl::setPhysicsActor(PhysicsEntity* pe)
{
	bulletActor = pe;
}

Ogre::Entity* EntityControl::getModelActor()
{
	return modelEntity;
}

void EntityControl::setModelActor(Ogre::Entity* entity)
{
	modelEntity = entity;
}

void EntityControl::causeDamage(float dmg)
{
	HitPoint-=dmg;
	if(HitPoint<=0)
		controller->kill();
}

void EntityControl::AddTrigger(Trigger *trigger)
{
	TriggerList.push_back(trigger);
}

Controller* EntityControl::getController()
{
 return controller;
}

Ogre::Vector3 EntityControl::getPosition()
{
	//return bulletActor->getCenterOfMassPosition();
	return Ogre::Vector3(bulletActor->getNxActor()->getCMassGlobalPosition().x, bulletActor->getNxActor()->getCMassGlobalPosition().y, bulletActor->getNxActor()->getCMassGlobalPosition().z);
}

